﻿(function ($) {

    $.fn.observer = function (fnPreparingData, fnSuccess) {
        return new rm.Observer($(this), fnPreparingData, fnSuccess);
    };

    rm.Observer = function (self, fnPreparingData, fnSuccess) {
        var owner = self;
        var fnPreparingDataCallback = fnPreparingData;
        var fnSuccessCallback = fnSuccess;
        var timer = -1;

        function update(options) {
            $(owner).find(".observer").each(function () {
                var dataSend = fnPreparingDataCallback(this);

                // send request to get data by Ajax
                Helpers.ajaxHelper.ajax({
                    type: options.type,
                    module: options.module,
                    controller: options.controller,
                    action: options.action,
                    contentType: options.contentType,
                    dataType: options.dataType,
                    showMask: false,
                    data: dataSend,
                    success: function (resultData) {
                        resultData = $.trim(resultData);
                        // update data by default
                        if (Helpers.isNull(fnSuccess)) {
                            var id = $(resultData).attr("id");
                            var elementView = $(owner).find("#" + id);
                            elementView.replaceWith($(resultData));
                        } else {
                            fnSuccessCallback(resultData);
                        }
                    }
                });
            });
        }

        rm.Observer.prototype.start = function (options, interval) {
            clearInterval(timer);
            timer = setInterval(function () {
                update(options);
            }, interval);
        };

        rm.Observer.prototype.stop = function () {
            clearInterval(timer);
        };
    };

})(jQuery, window.rm = window.rm || {});